package com.ztgf.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderDeadlineRecordMapper;
import com.ztgf.order.models.dto.OrderDeadlineRecordDTO;
import com.ztgf.order.models.service.IOrderDeadlineRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 订单截止时间记录表控制器
 *
 * @author chenyuwang
 * @Date 2021-03-11 09:44:09
 */
@Slf4j
@DubboService
public class OrderDeadlineRecordServiceImpl extends ServiceImpl<OrderDeadlineRecordMapper, OrderDeadlineRecordDTO> implements IOrderDeadlineRecordService {

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public void add(Long orderId, Integer state, Date date) {
        try {
            Wrapper<OrderDeadlineRecordDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("order_id", orderId);
            wrapper.eq("order_state", state);
            OrderDeadlineRecordDTO selectOne = this.selectOne(wrapper);
            if (selectOne != null) {
                return;
            }
            OrderDeadlineRecordDTO insertDto = new OrderDeadlineRecordDTO();
            insertDto.setId(ymlConfig.getPkId());
            insertDto.setOrderId(orderId);
            insertDto.setOrderState(state);
            insertDto.setEndTime(date);
            this.insert(insertDto);
        } catch (Exception e) {
            log.error("添加订单截止时间记录错误信息:{}", e.getMessage());
            e.printStackTrace();
        }

    }

    @Override
    public boolean insert(Long orderId, Integer state, Date date) {
        Wrapper<OrderDeadlineRecordDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("order_state", state);

        OrderDeadlineRecordDTO newDTO = new OrderDeadlineRecordDTO();

        newDTO.setOrderId(orderId);
        newDTO.setOrderState(state);
        newDTO.setEndTime(date);
        newDTO.setUpdateTime(new Date());
        if(!this.update(newDTO, wrapper)){
            newDTO.setId(ymlConfig.getPkId());
            if(!this.insert(newDTO)){
                return false;
            }
        }
        return true;
    }
}
